/* eslint-disable max-lines */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import AddForm from './components/AddForm';
import TicketTable from './components/TicketTable';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import DetailDrawer from './components/DetailDrawer';
import RefundPrice from './components/refund/RefundPrice';
import moment from 'moment';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import { areArraysEqual, arrayContrast } from './stores/method';
import ComponentsDrawer from '@/components/Drawers/ComponentsDrawer';
import useDebounce from '@/hooks/useDebounce';

const tableId = uniqueId('tauTable-');

const tabItems = [
  { key: '5', label: t`全部订单` },
  { key: '0', label: t`已取消` },
  { key: '1', label: t`已支付` },
  { key: '2', label: t`已完成` },
  { key: '4', label: t`已改签` },
  { key: '3', label: t`其他` },
  { key: '9', label: t`退款记录` },
];

function parseRegion(s) {
  if (!s?.length) return {};
  return { main: s[0]?.value, minor: s[2]?.id };
}

function BusOrder({ filter = {}, hideActions, hiddenSearchItems = [], queryParams }) {
  const [modal, setModal] = useState([]);
  const [expandAll, setExpandAll] = useState(false);
  const [companys, setCompanys] = useState([]);
  const { busOrderStore: store } = useStore();
  const orderRef = useRef();

  useEffect(() => {
    if (queryParams) {
      store.isView = true;
    }
    (async () => {
      const res = await store.getCompanys({ search: { isOperating: true } });
      setCompanys(res);
    })();
    return () => {
      store._orderStatus = '5';
      store.orders = [];
      store.isView = false;
      store.otherOrder = false;
    };
  }, []);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { orderDate, getOnDate, filterChangeOrder, startStations: __, endStations: ___, ...searchArgs } = params.values;
    const [from, to] = orderDate || [];
    const [fromTime, toTime] = getOnDate || [];
    const { startStations: start, endStations: end } = params.valueObjects;
    const { main: startMainArea, minor: startStations } = parseRegion(start?.selectedPath);
    const { main: endMainArea, minor: endStations } = parseRegion(end?.selectedPath);
    store.search = {
      ...filter,
      ...queryParams,
      from,
      to,
      fromTime,
      toTime,
      startMainArea,
      endMainArea,
      filterChangeOrder: filterChangeOrder && JSON.parse(filterChangeOrder),
      startStations: startStations && [startStations],
      endStations: endStations && [endStations],
      ...searchArgs,
    };
    // setExpandAll(false);
  };

  // 点击打开查看
  const handleView = (order) => {
    orderRef.current = order;
    setModal(['view']);
  };

  // 点击打开编辑
  const handleEdit = (order) => {
    orderRef.current = order;
    setModal(['edit']);
  };

  // 点击打开退款
  const handleRefund = (order) => {
    orderRef.current = order;
    setModal(['refund']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 变更数据提交
  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(result);
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleAdd = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.create(result);
        Message.success({ content: t`订单创建成功` });
      } catch (e) {
        Message.error({ content: t`订单创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 发起退款
  const handleOnRefund = useDebounce(async (result, state, type, account, otherAccount, open, accountSp) => {
    if (!_.isEmpty(result)) {
      try {
        let refundArgs = {};
        let args = {};
        const { id, cancelTime, refundPrice, distanceTime, cancelRemark = '', orderDetails, attachments, enableProfitShare, cancelCoupon } = toJS(result);
        const utcTime = moment.utc(cancelTime).subtract('8', 'hour').toISOString();
        /**
         * 退款逻辑 (退票和其他退款)
         * 1. 没有操作分账金额就给分账参数后端
         * 2. 页面上已经减去的退款金额要还原给后端
         * 3. 分账金额统一已 分 为单位
         */
        if (store._orderRefundStatus === '0') {
          const numberAccount = account.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          const computeAccount = arrayContrast(open, store.accounts, account);
          const orderTicket = orderDetails?.filter((item) => item.check && !item.disabled).map((p) => ({ ...p, ticketCode: p?.originalTicketCode || p.ticketCode }));
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            cancelCoupon,
            attachments: attachments || [],
            ticketRefundInfos: orderTicket,
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else if (store._orderRefundStatus === '1') {
          const numberAccount = otherAccount.map((item) => ({
            ...item,
            contributionAmount: Number(item.contributionAmount),
          }));
          const equal = areArraysEqual(store.initAccounts, numberAccount);
          const computeAccount = arrayContrast(open, store.accounts, otherAccount);
          refundArgs = {
            cancelTime: utcTime,
            refundPrice: Number(refundPrice).toFixed(2),
            distanceTime,
            cancelRemark,
            attachments: attachments || [],
            state,
            type,
            orderInfo: {
              orderId: id,
            },
          };
          /**
           * https://pm.aspiretop.com/issues/3179
           */
          if (!equal) {
            refundArgs.refundPayers = computeAccount;
          }
          args = {
            enableProfitShare,
          };
        } else {
          // 投诉索赔参数
          // https://pm.aspiretop.com/issues/3178
          const _account = _.cloneDeep(accountSp);
          const distributeInfos = [];
          for (let i = 0; i < _account.length; i++) {
            const { check, contributionAmount = 0, targetId, targetName, targetType } = _account[i];
            if (check) {
              distributeInfos.push({
                amount: contributionAmount * 100,
                targetId,
                targetName,
                targetType,
              });
            }
          }
          _.assign(args, {
            orderId: id,
            reason: cancelRemark,
            attachments: attachments || [],
            distributeInfos,
          });
        }
        if (store._orderRefundStatus === '0' || store._orderRefundStatus === '1') {
          await store.orderSponsorRefund(id, refundArgs, args);
        } else {
          // 线下支付 投诉索赔
          await store.orderCreateOffline(args);
        }
        Message.success({ content: t`申请退款成功` });
      } catch (e) {
        Message.error({ content: t`申请退款失败, ${e.message}`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
    // eslint-disable-next-line require-atomic-updates
    store._orderRefundStatus = '0';
  }, 200);

  const handleTableAction = (info, action) => {
    switch (action) {
      case 'view':
        handleView(info);
        break;
      case 'edit':
        handleEdit(info);
        break;
      case 'refund':
        handleRefund(info);
        break;
      case 'customerForm':
        handleOpenCustomer(info);
        break;
      default:
        break;
    }
  };

  const handleOpenCustomer = (order) => {
    orderRef.current = order;
    setModal(['customerForm']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={hideActions ? [] : [
          {
            name: 'btn-placeOrder',
            title: t`人工下单`,
            type: 'primary',
            onClick: () => setModal(['placeOrder']),
          },
          {
            name: 'btn-syncStatus',
            title: t`同步最近状态`,
            type: 'primary',
            onClick: async () => {
              try {
                await store.sync();
                Message.success({ content: t`同步成功` });
              } catch (e) {
                Message.success({ content: t`同步失败${e?.source}`, duration: 7000 });
              }
            },
          },
        ]}
        searchItems={store._orderStatus === '9' ?
          [
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`退款起始时间`, t`退款结束时间`],
              },
            },
            {
              name: 'state',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.state),
                placeholder: t`申请状态`,
              },
            },
            {
              name: 'type',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.refundType),
                placeholder: t`退款类型`,
              },
            },
          ]
          : [
            {
              name: 'orderDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始订单时间`, t`结束订单时间`],
              },
            },
            {
              name: 'ticketState',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.ticketStatus),
                placeholder: t`车票状态`,
              },
            },
            {
              name: 'isRoundTrip',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS.roundTrip),
                placeholder: t`单双程`,
              },
            },
            {
              name: 'getOnDate',
              type: 'date-range',
              props: {
                placeholder: [t`起始上车时间`, t`结束上车时间`],
              },
            },
            {
              name: 'startStations',
              type: 'bus-station',
              props: {
                placeholder: t`始发站点`,
                changeOnSelect: true,
                style: { minWidth: '160px' },
                forRoute: false,
                direction: '0',
              },
            },
            {
              name: 'endStations',
              type: 'bus-station',
              props: {
                placeholder: t`结束站点`,
                changeOnSelect: true,
                style: { minWidth: '160px' },
                forRoute: false,
                direction: '0',
              },
            },
            {
              name: 'companyId',
              type: 'select',
              props: {
                dataSource: companys,
                placeholder: t`承运公司`,
                style: { width: 150 },
              },
            },
            {
              name: 'filterChangeOrder',
              type: 'select',
              props: {
                dataSource: toSelectDataSource(ENUMS._filterChangeOrder),
                placeholder: t`是否改签后`,
              },
            },
          ].filter((si) => hiddenSearchItems.indexOf(si.name) === -1)}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          defaultActiveKey={'5'}
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.orders = [];
            store.orderStatus = v;
            store.otherOrder = !!queryParams;
          }}
          extra={store._orderStatus !== '9' &&
            <Button type="primary" onClick={() => setExpandAll(!expandAll)}>{expandAll ? t`合并全部` : t`展开全部`}</Button>
          }
        >
          {tabItems.map((item) => (<Tab.Item key={item.key} title={item.label} />))}
        </Tab>
        {store._orderStatus === '9' ? <TauTable
          instanceId={tableId}
          primaryKey="refundNumber"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          expandedRowIndent={[300, 100]}
          expandAll={expandAll}
          dataSource={toJS(store.orders)}
          columns={[
            { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('orderInfo.orderId', {
              width: 200,
              cell: (v, __, order) => {
                return <Button text type="primary" onClick={() => handleTableAction(order, 'view')}>{v}</Button>
              },
            }),
            column('applicationId', { width: 180 }),
            column('orderInfo.name', { width: 98 }),
            column('type', { width: 138 }),
            column('state', { width: 118 }),
            column('cancelTime', { width: 180 }),
            column('refundTime', { width: 180 }),
            column('refundPrice', { width: 118 }),
            column('cancelRemark', { width: 200 }),
          ].filter((c) => c.dataIndex !== 'action' || !hideActions)}
        /> : <TauTable
          instanceId={tableId}
          primaryKey="orderNumber"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          expandedRowRender={(row) => (
            <TicketTable
              busOrder={row.busOrder}
              orderId={row.id}
              changeAssociatedOrderIds={row?.changeAssociatedOrderIds}
              refundInfo={row.applicationRefunds}
              prices={row.busOrder?.prices}
            />
          )}
          expandedRowIndent={[300, 100]}
          expandAll={expandAll}
          dataSource={toJS(store.orders)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('orderNumber', {
              width: 188,
              cell: (v, __, order) => {
                const { orderDetails = [], companyId } = order?.busOrder;
                const { companies } = global.getEnvCfg();
                let isRed = null;
                //  中港通的车票由于删除了qrCodeInfo 还需再次使用 takeTicketCode 来判断
                if (companyId === companies?.ZGT?.id) {
                  isRed = orderDetails?.some(({ takeTicketCode }) => !!takeTicketCode);
                } else {
                  isRed = orderDetails?.some(({ qrCodeInfo }) => !!qrCodeInfo);
                }
                return <Button text style={{ color: !isRed && 'red' }} type="primary" onClick={() => handleTableAction(order, 'view')}>{v}</Button>;
              },
            }),
            column('busOrder.companyName', { width: 100 }),
            column('busOrder.type', { width: 58 }),
            column('busOrder.isRoundTrip', { width: 58 }),
            column('busOrder.routeText', { width: 100 }),
            column('busOrder.collectorName', {
              width: 58,
              cell: (v, i, r) => <Button type="primary" text onClick={() => handleTableAction(r, 'customerForm')}>{v}</Button>,
            }),
            column('price', { width: 118 }),
            column('busOrder.orderStatus', { width: 58 }),
            column('sourceGroup', { width: 200 }),
            column('changeAssociatedOrderIds', { width: 120 }),
            // column('source', { width: 100 }),
            // column('attributionName', { width: 100 }),
            // column('receiveName', { width: 100 }),
            column('crDate', { width: 124, sortable: true }),
            column('busOrder.shift.date', { width: 124, sortable: true }),
          ].concat((store._orderStatus === '9' || store._orderStatus === '5') ?
            [{
              title: t`操作`,
              dataIndex: 'action',
              width: 120,
              cell: (_, __, order) => {
                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleTableAction(order, 'edit'),
                  },
                  {
                    title: '退款',
                    onClick: () => handleTableAction(order, 'refund'),
                  },
                ];
                return (
                  <MoreFuncDropDown
                    dropdownItems={funcMenu}
                    maxShow={1}
                  />
                );
              },
            }] : []).filter((c) => c.dataIndex !== 'action' || !hideActions)}
        />}
      </div>
      <Drawer
        visible={modal[0] === 'placeOrder'}
        title={t`人工下单`}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <AddForm modal={modal} onCancel={handleCancel} onSubmit={handleAdd} />
      </Drawer>
      <Drawer
        visible={modal[0] === 'refund'}
        title={t`申请退款`}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
          store._orderRefundStatus = '0';
        }}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="80%"
      >
        <RefundPrice modal={modal} orderId={orderRef.current?.id} changeAssociatedOrderIds={orderRef.current?.changeAssociatedOrderIds} onCancel={handleCancel} onSubmit={handleOnRefund} />
      </Drawer>
      <DetailDrawer
        modal={modal}
        handleCancel={handleCancel}
        handleUpdate={handleUpdate}
        orderId={orderRef.current?.orderNumber || orderRef?.current?.orderInfo?.orderId}
        changeAssociatedOrderIds={orderRef.current?.changeAssociatedOrderIds}
        visible={modal[0] === 'view' || modal[0] === 'edit'}
        onClose={() => {
          setModal([...modal, `toClose$${Date.now()}`]);
        }}
      />
      <ComponentsDrawer modal={modal} queryParams={{ username: orderRef.current?.username }} name={orderRef.current?.busOrder?.fullname} onCancel={handleCancel} />
    </TauPage>
  );
}

export default observer(BusOrder);
